/************************************************
* 2020-07-25
* gky@qq.com
* 拖动控件
************************************************/

!function ($) {
	var win = $(window)
	$.fn.drag = function (margin, title) {
		title = title || '.Title'
		var start = this.children(title)
		var drag = this.css('position', 'fixed')
		start = start.length ? start : drag
		drag.move = false
		start.css('cursor', 'move').on('mousedown', function (event) {
			if (drag.move) return
			drag.move = true
			var offset = drag.offset()
			margin = $.dragMargin ? null : margin
			if(margin == 'left') {
				$.dragMargin = offset.left
			}else if(margin == 'top') {
				$.dragMargin = offset.top
			} else if (margin && typeof margin == 'number') {
				$.dragMargin = margin
			}
			drag.x = offset.left - event.clientX - win.scrollLeft()
			drag.y = offset.top - event.clientY - win.scrollTop()
 			var mousemove = function (event) {
				if (!drag.move) return
				drag.css({
					top: event.clientY + drag.y,
					left: event.clientX + drag.x,
				})
				return false
			}
			var mouseup = function () {
				var margin = $.dragMargin || 0
				var animate = drag.offset()
				if (animate.top + drag.height() + margin > win.height()) animate.top = win.height() - drag.height() - margin
				if (animate.top < margin) animate.top = margin
				if (animate.left + drag.width() + margin > win.width()) animate.left = win.width() - drag.width() - margin
				if(animate.left < margin) animate.left = margin
				drag.animate(animate, 200)
				drag.move = false
				win.off('mousemove', mousemove).off('mouseup', mouseup)
			}
			win.on('mousemove', mousemove).on('mouseup', mouseup)
			event.stopPropagation()
		})
		return this
	}

}(window.$)